<?php
/*********************************************************************************
 * Copyright (C) 2011-2013 X2Engine Inc. All Rights Reserved.
 *
 * X2Engine Inc.
 * P.O. Box 66752
 * Scotts Valley, California 95067 USA
 *
 * Company website: http://www.x2engine.com
 * Community and support website: http://www.x2community.com
 *
 * X2Engine Inc. grants you a perpetual, non-exclusive, non-transferable license
 * to install and use this Software for your internal business purposes.
 * You shall not modify, distribute, license or sublicense the Software.
 * Title, ownership, and all intellectual property rights in the Software belong
 * exclusively to X2Engine.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 ********************************************************************************/

/* @edition:pro */

Yii::app()->clientScript->registerCoreScript('cookie');

$cookies = Yii::app()->request->cookies;
$showLabels;
if ((string) $cookies['x2flowShowLabels']) {
    $showLabels = $cookies['x2flowShowLabels']->value === 'false' ? false : true;
} else {
    $showLabels = true;
}


$newRecord = $model->isNewRecord;

// Yii::app()->clientScript->registerScript('vcrListCookie', "
// $('#content').on('mouseup','#contacts-grid a',function(e) {
    // document.cookie = 'vcr-list=".$listId."; expires=0; path=/';
// });
// ",CClientScript::POS_READY);

$modelsWithInsertableAttrs = array (
    'Accounts', 'Actions', 'Contacts', 'Docs', 'Groups', 'Campaign', 'Media', 'Opportunity',
    'Product', 'Quote', 'Services', 'BugReports');


$insertableAttributes = array();
foreach ($modelsWithInsertableAttrs as $modelName) {
    $insertableAttributes[$modelName] = array ();
    foreach(X2Model::model($modelName)->attributeLabels() as $fieldName => $label) {
        $insertableAttributes[$modelName][$label] = '{'.$fieldName.'}';
    }
}

$translations = array (
    'x2flow-empty' => Yii::t('studio',  ''),
    'ActionCompleteTrigger' => Yii::t('studio',  'Completed'),
    'ActionOverdueTrigger' => Yii::t('studio',  'Overdue'),
    'ActionUncompleteTrigger' => Yii::t('studio',  'Incomplete'),
    'CampaignEmailClickTrigger' => Yii::t('studio',  'Clicked'),
    'CampaignEmailOpenTrigger' => Yii::t('studio',  'Opened'),
    'CampaignUnsubscribeTrigger' => Yii::t('studio',  'Unsubscribed'),
    'CampaignWebActivityTrigger' => Yii::t('studio',  'Web Activity'),
    'NewsletterEmailClickTrigger' => Yii::t('studio',  'Clicked'),
    'NewsletterEmailOpenTrigger' => Yii::t('studio',  'Opened'),
    'NewsletterUnsubscribeTrigger' => Yii::t('studio',  'Unsubscribed'),
    'NewsletterWebActivityTrigger' => Yii::t('studio',  'Web Activity'),
    'RecordCreateTrigger' => Yii::t('studio',  'Created'),
    'RecordDeleteTrigger' => Yii::t('studio',  'Deleted'),
    'RecordTagAddTrigger' => Yii::t('studio',  'Tag Added'),
    'RecordTagRemoveTrigger' => Yii::t('studio',  'Tag Removed'),
    'RecordUpdateTrigger' => Yii::t('studio',  'Updated'),
    'RecordViewTrigger' => Yii::t('studio',  'Viewed'),
    'UserLoginTrigger' => Yii::t('studio',  'Sign In'),
    'UserLogoutTrigger' => Yii::t('studio',  'Sign Out'),
    'WebActivityTrigger' => Yii::t('studio',  'Web Activity'),
    'WebleadTrigger' => Yii::t('studio',  'Web Lead')
);

$translations['templateChangeConfirm'] =
    Yii::t('app','Note: you have entered text into the email that will be lost.'.
        ' Are you sure you want to continue?');

//$requiresCron = array ('X2FlowWait', 'NewsletterWebActivityTrigger');

$passVarsToClientScript = '
    x2.flow = {};
    x2.flow.translations = {};
    x2.flow.requiresCron = '.CJSON::encode ($requiresCron).';
    x2.flow.showLabels = '.($showLabels ? 'true' : 'false').';
    x2.flow.insertableAttributes = '.
        CJSON::encode ($insertableAttributes).';
    x2.flowData = '.CJSON::encode($model->flow).';
    x2.operatorList = '.CJSON::encode(X2FlowTrigger::getComparisonOptions()).';
    x2.visibilityOptions = '.CJSON::encode(array(
        array(1,Yii::t('app','Public')),
        array(0,Yii::t('app','Private')),
        array(2,Yii::t('app','User\'s Groups'))
    )).';
    x2.allTags = '.CJSON::encode(Tags::getAllTags()).';
';

// pass array of predefined theme uploadedBy attributes to client
foreach ($translations as $key=>$val) {
    $passVarsToClientScript .= "x2.flow.translations['".
        $key. "'] = '" . addslashes ($val) . "';\n";
}

Yii::app()->clientScript->registerScript(
    'passVarsToX2FlowScript', $passVarsToClientScript,
    CClientScript::POS_HEAD);

$assets = Yii::app()->getAssetManager()->publish(
    Yii::getPathOfAlias('application.extensions.CJuiDateTimePicker').DIRECTORY_SEPARATOR.'assets'
);
$cs = Yii::app()->getClientScript();
$cs->registerCssFile($assets.'/jquery-ui-timepicker-addon.css');
$cs->registerScriptFile($assets.'/jquery-ui-timepicker-addon.js',CClientScript::POS_END);

// Yii::app()->clientScript->registerScript('flowParams','var flowParams = '.CJSON::encode($flowParamData).';',CClientScript::POS_HEAD);

$cs->registerScriptFile(Yii::app()->getBaseUrl().'/js/x2fields.js');
$cs->registerScriptFile(Yii::app()->getBaseUrl().'/js/x2flowEditor.js');
$cs->registerCssFile(Yii::app()->theme->getBaseUrl().'/css/x2flow.css');

// used for rich editing in item config forms
$cs->registerScriptFile(Yii::app()->getBaseUrl().'/js/ckeditor/ckeditor.js');
$cs->registerScriptFile(Yii::app()->getBaseUrl().'/js/ckeditor/adapters/jquery.js');
$cs->registerScriptFile(Yii::app()->request->baseUrl . '/js/emailEditor.js');

$cs->registerScriptFile(Yii::app()->theme->getBaseUrl().'/css/listview/jquery.yiigridview.js');


Yii::app()->clientScript->registerScript('flowEditorScript','

    function flowEditorMain () {

        $("#show-trace-button").on ("click", function () {
            $("#x2flow-trace-box").slideToggle ();
        });

        // shows/hides flow item labels
        $("#x2flow-show-labels-checkbox").on ("change", function () {
            if (this.checked) { // show labels
                $(".x2flow-main").find (".x2flow-icon-label").show ();
                $(".x2flow-node.x2flow-action").each (function () {
                    if ($(this).children ().first ().hasClass ("x2flow-icon-label")) {
                        $(this).children ().first ().attr ("style", "");
                    }
                });
                $(".x2flow-node").each (function () {
                    if ($(this).children ().first ().hasClass ("x2flow-icon-label")) {
                        $(this).removeClass ("no-label"); // used to position arrows
                    }
                });
                $("#trigger").find (".x2flow-icon-label").attr ("style", "");
                $("#trigger").removeClass ("no-label");
                $.cookie ("x2flowShowLabels", "true");
                x2.flow.showLabels = true;
            } else { // hide labels
                $(".x2flow-main").find (".x2flow-icon-label").hide ();
                $(".x2flow-node.x2flow-action").each (function () {
                    if ($(this).children ().first ().hasClass ("x2flow-icon-label")) {
                        $(this).children ().first ().attr ("style", "display: none;");
                    }
                });
                $(".x2flow-node").each (function () {
                    if ($(this).children ().first ().hasClass ("x2flow-icon-label")) {
                        $(this).addClass ("no-label"); // used to position arrows
                    }
                });
                $("#trigger").find (".x2flow-icon-label").attr ("style", "display: none;");
                $("#trigger").addClass ("no-label");
                $.cookie ("x2flowShowLabels", "false");
                x2.flow.showLabels = false;
            }
        });

        $("#test-cron-button").on ("click", function () {
            if ($(this).attr ("disabled")) return;
            $.ajax ({
                "url": '.CJSON::encode($this->createUrl('api/x2cron')).',
                "success": function (data) {
                    auxlib.createReqFeedbackBox ({
                        prevElem: $("#test-cron-button"),
                        message: "'.Yii::t('studio','Cron Action Succeeded').'",
                        delay: 3000,
                        classes: ["right"]
                    });
                },
                "error": function () {
                    auxlib.createReqFeedbackBox ({
                        prevElem: $("#test-cron-button"),
                        message: "'.Yii::t('studio','Cron Action Failed').'",
                        delay: 3000,
                        classes: ["right"]
                    });
                }
            });
        });

        // show cron log
        $("#view-log-button").on ("click", function () {
            if ($(this).attr ("disabled")) return;
            $("#view-log-button").attr ("disabled", "disabled");
            $.ajax ({
                "url": '.CJSON::encode($this->createUrl('admin/viewLog',array('name' => 'automation.log'))).',
                "success": function (data) {
                    $("body").append($("<div>", {
                        id: "cron-log-dialog",
                        html: data
                    }).css({
                        "max-height":"500px",
                        "overflow-x":"hidden"
                    }));
                    $("#cron-log-dialog").dialog ({
                        autoOpen: true,
                        maxHeight: "500px",
                        title: '.CJSON::encode(Yii::t('studio','Viewing log file {file}',array('{file}'=>'automation.log'))).',
                        width: "auto",
                        resizable: true,
                        close: function (event, ui) {
                            $("#cron-log-dialog").remove ();
                            $("#view-log-button").removeAttr ("disabled");
                        }
                    });
                }
            });
        });
    }

    $(document).on ("ready", flowEditorMain);

', CClientScript::POS_HEAD);


$this->actionMenu = array(
    array('label'=>Yii::t('studio','Manage Flows'), 'url'=>array('flowIndex')),
);
if($model->isNewRecord) {
    $this->actionMenu[] = array('label'=>Yii::t('studio','Create Flow'));
} else {
    $this->actionMenu[] = array('label'=>Yii::t('studio','Create Flow'), 'url'=>array('flowDesigner'));
    // $this->actionMenu[] = array('label'=>Yii::t('module','Edit'), 'url'=>array('flowDesigner', 'id'=>$model->id));
    $this->actionMenu[] = array('label'=>Yii::t('module','Update'));
    $this->actionMenu[] = array('label'=>Yii::t('module','Delete'), 'url'=>'#', 'linkOptions'=>array('submit'=>array('deleteFlow','id'=>$model->id),'confirm'=>Yii::t('app','Are you sure you want to delete this item?')));
}

$this->actionMenu[] = array (
    'label' => Yii::t('studio', 'All Trigger Logs'),
    'url' => array ('triggerLogs')
);

$shortTitles = array (
    'Remote API Call' => 'API Call',
    'Create Action' => '+ Action',
    'Post to Activity Feed' => 'Feed Post',
    'Email' => 'Email',
    'Add Comment' => 'Comment',
    'Create Record' => '+ Record',
    'Create Popup Notification' => 'Notify',
    'Create Action for Record' => '+ Action',
    'Delete Record' => 'Remove',
    'Email Contact' => 'Email',
    'Add to List' => '+ to List',
    'Remove from List' => 'Remove',
    'Reassign Record' => 'Reassign',
    'Add or Remove Tags' => '+/- Tags',
    'Update Record' => 'Update',
    'Wait' => 'Wait'
);

$actionMenuHtml = '
<div id="item-box">
<div class="x2flow-node X2FlowSwitch" style="">
    <span>'.Yii::t('studio','Condition').'</span>
    <div class="icon">
        <div class="x2flow-yes-label">'.Yii::t('app','Yes').'</div>
        <div class="x2flow-no-label">'.Yii::t('app','No').'</div>
    </div>
    <div class="x2flow-branch-wrapper">
        <div class="x2flow-branch">
            <div class="bracket"></div>
            <div class="x2flow-node x2flow-empty"></div>
        </div>
        <div class="x2flow-branch">
            <div class="bracket"></div>
            <div class="x2flow-node x2flow-empty"></div>
        </div>
    </div>
</div>';
foreach($actionTypes as $type => $title) {
    if(stripos($type,'workflow') === false)
        $actionMenuHtml .=
            '<div class="x2flow-node x2flow-action '.$type.
              ($showLabels ? "" : " no-label").'"
              title="'.addslashes(Yii::t('studio',$title)).'">
                <div class="x2flow-icon-label" '.($showLabels ? "": "style='display: none;'").'>'.(isset($shortTitles[$title])?Yii::t('studio',$shortTitles[$title]):'').'</div>

                <span>'.Yii::t('studio',$title).'</span>
             </div>';
}
$actionMenuHtml .= '</div>';

$this->leftPortlets[] = array(
    'options'=>array('title'=>Yii::t('studio','Flow Actions'),'id'=>'flow-actions'),
    'content'=>$actionMenuHtml
);

// if(!empty($flowData))
    // Yii::app()->clientScript->registerScript('vcrListCookie', 'var flowData = '.CJSON::encode($flowData),CClientScript::POS_READY);





?>
<!--
<div class="page-title"></div><span class="no-bold"></span>


        'summaryText'=>Yii::t('app','<b>{start}&ndash;{end}</b> of <b>{count}</b>'),
-->
<div class="page-title icon x2flow">
    <h2><?php echo $model->isNewRecord? Yii::t('studio','Create Flow') : Yii::t('admin','Update Flow'); ?></h2>
    <a class="x2-button btn btn-mini  btn-yellow highlight right" id="save-button" href="javascript:void(0);"><?php echo Yii::t('app','Save'); ?></a>
    <?php
    if (isset ($triggerLogsDataProvider)) {
    ?>
    <a class="x2-button btn btn-small  btn-light  right" id="show-trace-button" href="javascript:void(0);">
        <?php echo Yii::t('studio','Show Trigger Logs'); ?>
    </a>
    <?php
    }
    ?>
    <a class="x2-button btn btn-small  btn-light  right" id="view-log-button" style="display: none;" href="javascript:void(0);">
        <?php echo Yii::t('studio','View Cron Log'); ?>
    </a>
    <a class="x2-button btn btn-small  btn-light  right" id="test-cron-button" style="display: none;" href="javascript:void(0);">
        <?php echo Yii::t('studio','Test Cron'); ?>
    </a>
</div>
<div class="form x2flow-start">
    <?php $form = $this->beginWidget('CActiveForm',array('id'=>'submitForm','enableAjaxValidation'=>false)); ?>
    <?php echo $form->errorSummary($model); ?>
    <div class="row">
        <div class="form x2flow-trash"></div>
        <!--<div class="cell">
            <div class="x2flow-node x2flow-trigger x2flow-empty" id="trigger" title="<?php echo addslashes(Yii::t('studio','Select a trigger')); ?>"></div>
        </div>-->
        <div class="cell">
            <?php echo $form->label($model,'triggerType'); ?>
            <?php echo CHtml::dropdownList('trigger-selector','',
                array_merge(array('x2flow-empty'=>Yii::t('studio','Select a trigger')),$triggerTypes),
                array('id'=>'trigger-selector'
            )); ?>
        </div>
        <div class="cell">
            <?php echo $form->label($model,'name'); ?>
            <?php echo $form->textField($model,'name'); ?>
            <?php echo $form->hiddenField($model,'flow',array('id'=>'flowDataField')); ?>
        </div>
        <div class="cell">
            <?php echo $form->label($model,'active'); ?>
            <?php echo $form->dropdownList($model,'active',array(1=>Yii::t('app','Yes'),0=>Yii::t('app','No'))); ?>
        </div>
        <div class="cell right" id='x2flow-show-labels-checkbox-container'>
            <input id='x2flow-show-labels-checkbox' type='checkbox' class='right'
             <?php echo ($showLabels ? "checked='checked'" : ''); ?>>
            <label for='x2flow-show-labels-checkbox' class='right'>
                <?php echo CHtml::encode (Yii::t('studio', 'Toggle Node Labels')); ?>
            </label>
        </div>
    </div>
    <?php $this->endWidget(); ?>
</div>
<div class="form x2flow-main" id="x2flow-main">
    <div class="x2flow-node x2flow-trigger x2flow-empty
     <?php echo ($showLabels ? "" : " no-label"); ?>"
     id="trigger" title="<?php echo addslashes(Yii::t('studio','Select a trigger')); ?>">
        <div class="x2flow-icon-label" <?php echo ($showLabels ? "": "style='display: none;'") ?>></div>
    </div>
    <div class="x2flow-branch">
        <div class="bracket hidden"></div>
        <div class="x2flow-node x2flow-empty"></div>
    </div>
</div>
<?php
/*
<b>Free For All</b><br>
Assigns all web leads to "Anyone" and users can re-assign to themselves.<br><br>
<b>Even Distribution</b><br>
Assigns web leads to whomever has the lowest number of uncompleted actions, evening out the number of uncompleted actions between users.<br><br>
<b>Round Robin</b><br>
Assigns leads to each user going through the list one by one. <br><br>
<b>Custom Round Robin</b><br>
Same as above but allows you to set custom rules.  i.e. if a contact comes in with a specific value, it will be distributed to a group of users you specify.
This option will not work unless you create custom rules.<br><br>
<b>Single User</b><br>
The Single User option will assign all leads to the specified user.
<br><br><br>
<b>Online Only</b><br>
This option will filter your routing rule so that leads only go to a subset of the users who are logged in.
i.e. if you set custom rules to go to 4 different users, but 2 are logged in, only those 2 will get the leads
 */
?>
<div class="form" id="x2flow-config-box">
    <div id="x2flow-main-config"></div><hr>
    <div id="x2flow-conditions" class="x2-sortlist"><ol></ol></div>
    <div id="x2flow-attributes" class="x2-sortlist"><ol></ol></div>
    <div>
        <?php echo CHtml::dropdownList(
            'type','',X2FlowTrigger::getGenericConditions(),
            array('id'=>'x2flow-condition-type','style'=>'display:none;')); ?>
        <?php echo CHtml::button(
            Yii::t('studio','Add Condition'),
            array('id'=>'x2flow-add-condition','class'=>'x2-button btn btn-mini  btn-yellow','style'=>'display:none;')); ?>
    </div>
    <?php echo CHtml::button(
        Yii::t('studio','Add Attribute'),
        array('id'=>'x2flow-add-attribute','class'=>'x2-button btn btn-mini  btn-yellow','style'=>'display:none;')); ?>
</div>

<?php

if (isset ($triggerLogsDataProvider) && isset ($model->id)) {
    $this->renderPartial (
        '_triggerLogsGridView', array (
            'triggerLogsDataProvider' => $triggerLogsDataProvider,
            'flowId' => $model->id,
            'parentView' => 'flowEditor'
        )
    );
}
?>

<!-- HTML templates -->
<div id="item-delete"></div>
<div id="condition-templates" style="display:none;">
    <ol><li><div class="handle"></div><fieldset></fieldset><a href="javascript:void(0)" class="del"></a></li></ol>
    <div class="cell x2fields-attribute">
        <!--<label><?php echo Yii::t('studio','Attribute'); ?></label>-->
        <select name="attribute"></select>
    </div>
    <div class="cell x2fields-operator">
        <!--<label><?php echo Yii::t('studio','Comparison'); ?></label>-->
        <select name="operator"></select>
    </div>
    <div class="cell x2fields-value">
        <!--<label><?php echo Yii::t('studio','Value'); ?></label>-->
        <input type="text" />
    </div>
    <fieldset class="API_params">
        <div class="cell x2fields-attribute">
            <label><?php echo Yii::t('studio','Name'); ?></label>
            <input type="text" name="attribute" />
        </div>
        <div class="cell x2fields-value">
            <label><?php echo Yii::t('studio','Value'); ?></label>
            <input type="text" name="value" />
        </div>
    </fieldset>
</div>
<!-- end templates -->
